<template>
  <div class="root-house-mng">
    <div class="root-house-mng-main">
      <ImagePreview :imageList="imgList" />

      <HouseMap
        mapViewId="houseStatMap"
        :showMapPopupButtons="showMapPopupButtons"
        @on-popup-button-ok-click="onPopupButtonOkClick"
        @on-popup-button-fire-click="onPopupButtonFireClick"
        @on-popup-button-police-click="onPopupButtonPoliceClick"
        @on-popup-button-zhujian-click="onPopupButtonZhujianClick"
        ref="houseMapRef"
      />
    </div>

    <AuditModal @register="registerModal" @success="handleSuccess" />

    <Drawer5 @register="register5">
      <template #drawContent>
        <DataTableList
          v-if="!pickedPlaceId && policeVisibleRef"
          :houseId="pickedHouseId"
          ref="housePolicePlaceRef"
          @house-submit="handleSuccess"
          
        />
        <FireTableList
          v-if="!pickedPlaceId && fireVisibleRef"
          :houseId="pickedHouseId"
          ref="houseFirePlaceRef"
          @house-submit="handleSuccess"
        />
        <PoliceTableDetail
          v-if="pickedPlaceId && pickedPlaceDomainType == 'police'"
          :hid="pickedHouseId"
          :pid="pickedPlaceId"
          :typ="pickedPlaceType"
          ref="detailViewPoliceRef"
        />
      </template>
    </Drawer5>

    <Drawer5 @register="register6">
      <template #drawContent>
        <DetailCheckView
          v-if="zjHouseInfoVisibleRef"
          :hid="pickedHouseId"
          :checkForms="houseCheckInfoForm"
        />
      </template>
    </Drawer5>
  </div>
</template>

<script lang="ts">
//import maplibregl from '/@/utils/lib/mapre/maplibre-gl.js';
//import '/@/utils/lib/mapre/maplibre-gl.css';
import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getBasicColumns, tablePopupSchema } from './tableData';
import { PageWrapper } from '/@/components/Page';
import { BasicForm, useForm } from '/@/components/Form/index';
import { Tabs, Space, Divider, Drawer, Tag, Collapse, Button, Popover } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  ComputedRef,
  computed,
  defineAsyncComponent,
  nextTick,
} from 'vue';
import { houseListApi, houseZhujianApi, houseCheckListApi, houseCheckApi } from '/@/api/demo/table';
import { placeListApi, delPlace } from '/@/api/demo/system';
import * as tableDataPopup from '/@/views/map/tableDataPopup';
import { useGlobSetting } from '/@/hooks/setting';
const globSetting = useGlobSetting();
import { getSearchFormSchema } from '/@/views/house/tableData';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
const { info, success, warning, error } = createMessage;
import { FormProps, FormSchema } from '/@/components/Table';
import AuditModal from './AuditModal.vue';
import HouseMap from './HouseMap2.vue';
import { useModal } from '/@/components/Modal';
import type { UserInfo } from '/#/store';
import { SearchOutlined } from '@ant-design/icons-vue';
import Drawer5 from '/@/views/detail/Drawer5.vue';
import { useDrawer } from '/@/components/Drawer';
const DataTableList = defineAsyncComponent(
  () => import('/@/views/village/threePure/cjworkstaticMap/component/checkDetailDrawer.vue'),
);

const FireTableList = defineAsyncComponent(
  () => import('/@/views/danger/fire/FireTableListMergeAll.vue'),
);
const PoliceTableDetail = defineAsyncComponent(
  () => import('/@/views/danger/comprehensive/detail.vue'),
);
const DetailCheckView = defineAsyncComponent(() => import('./detail.vue'));
const FireTableDetail = defineAsyncComponent(() => import('/@/views/danger/fire/detail.vue'));
const imgList: string[] = [];
export default defineComponent({
  name: 'HouMng',
  components: {
    DataTableList,
    FireTableList,
    PoliceTableDetail,
    FireTableDetail,
    DetailCheckView,
    ImagePreview,
    BasicTable,
    BasicForm,
    AuditModal,
    TableAction,
    PageWrapper,
    Tabs,
    Divider,
    Drawer5,
    Space,
    SearchOutlined,
    Popover,
    HouseMap,
    Tag,
    TabPane: Tabs.TabPane,
    Button,
  },
  props: {
    msg: String,
    showMapPopupButtons: {
      type: Boolean,
      default: true,
    },
    policeVisible: {
      type: Boolean,
      default: false,
    },
    fireVisible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { attrs, emit, slots, expose }) {
    const activeKeyRef = ref('map');
    const activePickKeyRef = ref('fire');
    const searchVisible = ref(false);
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;

    const pickedHouse = ref({});
    const pickedHouseId = ref('');
    const pickedPlaceId = ref('');
    const pickedPlaceType = ref(0);
    const pickedPlaceDomainType = ref('');
    const houseFirePlaceRef = ref();
    const housePolicePlaceRef = ref();

    // 计算属性基本使用
    const zjHouseInfoVisibleRef = ref(false);
    const houseMapRef = ref();
    const policeVisibleRef = ref(props.policeVisible);
    const fireVisibleRef = ref(props.fireVisible);

    const userStore = useUserStore();

    const detailViewFireRef = ref();
    const detailViewPoliceRef = ref();

    const houseCheckInfoForm = ref({});

    function calcModes(user: UserInfo) {
      if (user) {
        if ('Admin' == user.role) {
          return ['fire', 'police', 'housing'];
        } else {
          if ('FireControl' == user.userGroup) {
            return ['fire'];
          } else if ('Police' == user.userGroup) {
            return ['police'];
          } else if ('Housing' == user.userGroup) {
            return ['housing'];
          }
        }
      }

      return [];
    }

    function getTableActs(record) {
      let acts = [
        {
          icon: 'clarity:note-edit-line',
          tooltip: '修改状态',
          onClick: handleStatus.bind(null, record),
        },
        {
          icon: 'clarity:map-marker-line',
          tooltip: '定位',
          onClick: handleLocMap.bind(null, record),
        },
      ];

      if (props.showMapPopupButtons) {
        acts.push({
          icon: 'clarity:tree-view-line',
          tooltip: '查看场所',
          onClick: handlePlaceView.bind(null, record),
        });
      }

      return acts;
    }

    const underMode = calcModes(userStore.getUserInfo);

    const tk = userStore.getToken;
    let protocol = window.document.location.protocol;
    let host = window.document.location.host;
    let localhostPath = protocol + '//' + host;

    const mapopC: maplibregl.Popup[] = [];
    function clickPopUpOk(_) {
      if (mapopC.length > 0) {
        mapopC[0].remove();
      }
    }

    const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();
    const [register6, { openDrawer: openDrawer6, setDrawerProps: setDrawerProps6 }] = useDrawer();

    function clickPopupButtonOk(obj) {
      pickedHouse.value = obj;
      pickedHouseId.value = obj.id;
      pickedPlaceId.value = '';
      placeListApi({
        id: obj.fwbh,
        page: 15,
        pageSize: 2,
      }).then((resp) => {
        if (resp.total == 1) {
          pickedPlaceId.value = resp.items[0].id;
          pickedPlaceType.value = resp.items[0].type;
        }

        setDrawerProps({
          destroyOnClose: true,
          showDetailBack: false,
          afterVisibleChange: (visible: boolean) => {
            if (visible && pickedPlaceId.value) {
              if (pickedPlaceDomainType.value == 'fire') {
                  detailViewFireRef.value.locMap();
              } else if (pickedPlaceDomainType.value == 'police') {
                detailViewPoliceRef.value.locMap();
              }
            }
          },
        });
        openDrawer5(true);
      });
    }

    const [registerModal, callbackUseModal] = useModal();

    function cloneSearchSchema(serSchema: FormSchema[]) {
      var serSchemaClone: FormSchema[] = [];
      serSchema.forEach((ele) => {
        const a: FormSchema = Object.assign({}, ele);
        a.colProps = { span: 12, flex: 1 };
        serSchemaClone.push(a);
      });

      return serSchemaClone;
    }

    var serSchema = getSearchFormSchema(underMode);

    const [registerTable, { reload }] = useTable({
      api: houseListApi,
      columns: getBasicColumns(),
      pagination: { pageSize: 10 },
      formConfig: {
        schemas: cloneSearchSchema(serSchema),
      },
      useSearchForm: true,
      bordered: true,
      actionColumn: {
        width: 120,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
    });
    function handleReloadCurrent() {
      reload();
    }

    function handleReload() {
      reload({
        page: 1,
      });
    }

    function handleSuccess() {
      reload();
    }

    function handlePreview(record: Recordable) {
      const onImgLoad = ({ index, url, dom }) => {
        console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
      };
      imgList.length = 0;
      if (record.photos) {
        let photos = record.photos.split(',');
        photos.forEach((ele) => {
          if (ele) imgList.push(`${globSetting.apiBaseUrl}/api/v1/images111/${ele}`);
        });
      }
      // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
      createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
    }

    function handleStatus(record: Recordable) {
      callbackUseModal.openModal(true, {
        record,
        isUpdate: true,
      });
    }

    function onPopupButtonOkClick(obj) {
      pickedPlaceDomainType.value = '';
      clickPopupButtonOk(obj);
    }
    function onPopupButtonFireClick(obj) {
      policeVisibleRef.value = false;
      fireVisibleRef.value = true;
      pickedPlaceDomainType.value = 'fire';
      clickPopupButtonOk(obj);
    }
    function onPopupButtonPoliceClick(obj) {
      policeVisibleRef.value = true;
      fireVisibleRef.value = false;
      pickedPlaceDomainType.value = 'police';
      clickPopupButtonOk(obj);
    }

    function openZjHouseInfoView() {
      setDrawerProps6({
        destroyOnClose: true,
        showDetailBack: false,
        afterVisibleChange: (visible: boolean) => {
          if (visible) {
          }
        },
        onClose: (e: Event) => {
          zjHouseInfoVisibleRef.value = false;
        },
      });
      zjHouseInfoVisibleRef.value = true;
      openDrawer6(true);
    }

    function onPopupButtonZhujianClick(obj) {
      pickedPlaceDomainType.value = '';
      pickedHouse.value = obj;
      pickedHouseId.value = obj.id;
      pickedPlaceId.value = '';
      houseCheckInfoForm.value = { form: [] };
      houseZhujianApi({ id: obj.id })
        .then((res) => {
          houseCheckInfoForm.value = res;
          openZjHouseInfoView();
        })
        .catch((err) => {
          openZjHouseInfoView();
        });
    }

    function handlePlaceView(record: Recordable) {
      clickPopupButtonOk(record);
    }

    function handleLocMap(record: Recordable) {
      activeKeyRef.value = 'map';
      houseMapRef.value.handleLocMap(record);
    }

    function locMap(houseId) {
      houseMapRef.value.locMap(houseId);
    }

    const getFormProps = computed((): Partial<FormProps> => {
      return {
        showAdvancedButton: false,
        compact: true,
        actionColOptions: { span: 6 },
        schemas: cloneSearchSchema(serSchema),
      };
    });

    function handleSearchInfoChange(info: Recordable) {}
    const [registerForm, formActions] = useForm();
    const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
      const keys = Object.keys(slots);
      return keys
        .map((item) => (item.startsWith('form-') ? item : null))
        .filter((item) => !!item) as string[];
    });
    function replaceFormSlotKey(key: string) {
      if (!key) return '';
      return key?.replace?.(/form\-/, '') ?? '';
    }
    const showDrawer = () => {
      searchVisible.value = true;
    };

    return {
      zjHouseInfoVisibleRef,
      imgList,
      activeKeyRef,
      activePickKeyRef,
      registerForm,
      getFormSlotKeys,
      replaceFormSlotKey,
      getFormProps,
      handleSearchInfoChange,
      registerTable,
      handlePreview,
      handleLocMap,
      handleStatus,
      handleReloadCurrent,
      handleReload,
      locMap,
      registerModal,
      handleSuccess,
      searchVisible,
      showDrawer,
      register5,
      register6,
      pickedHouse,
      pickedHouseId,
      pickedPlaceId,
      pickedPlaceType,
      pickedPlaceDomainType,
      houseFirePlaceRef,
      housePolicePlaceRef,
      houseMapRef,
      getTableActs,
      onPopupButtonOkClick,
      onPopupButtonFireClick,
      onPopupButtonPoliceClick,
      onPopupButtonZhujianClick,
      handlePlaceView,
      policeVisibleRef,
      fireVisibleRef,
      detailViewFireRef,
      detailViewPoliceRef,
      houseCheckInfoForm,
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  //z-index: 100;
  //position: absolute;
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;
  //background-color: rgba(34, 34, 34, 0.6);
  :deep(.ant-form) {
    margin-top: 6px;
  }

  // :deep(.ant-form-item-label) > label {
  //   color: white;
  // }
}
</style>
